package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.entity.AjaxResult;
import org.example.entity.Token;
import org.example.security.UserDetailsImpl;
import org.example.service.impl.TokenService;
import org.example.vo.LoginVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
public class LoginController {

    private final TokenService tokenService;
    private final AuthenticationManager authenticationManager;

//    @PostMapping("/login")
//    public AjaxResult login(LoginVO loginVO){
//        Token token=tokenService.createToken(loginVO);
//        return AjaxResult.ok(token);
//    }

//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody LoginVO loginVO){
//        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVO.getName(),loginVO.getPassword());
//        try {
//            SecurityUtils.getSubject().login(usernamePasswordToken);
//        } catch (UnknownAccountException e) {
//            return AjaxResult.error("用户不存在");
//        } catch (AuthenticationException e) {
//            return AjaxResult.error("用户名或密码错误");
//        }
//        return AjaxResult.ok();
//    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginVO){
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginVO.getName(),loginVO.getPassword());
//        该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        Token token=tokenService.createToken((UserDetailsImpl)authenticate.getPrincipal());
        return AjaxResult.ok(token);
    }

    @GetMapping("/logout")
    public AjaxResult logout(@RequestHeader String token){
        tokenService.removeToken(token);
        return AjaxResult.ok();
    }
}
